package com.community.auth.controller;

import com.alibaba.fastjson.JSON;
import com.community.auth.vo.LoginVo;
import com.community.common.core.constant.RedisKey;
import com.community.common.core.exception.CommunityException;
import com.community.common.core.utils.JWTUtils;
import com.community.common.core.utils.Result;
import com.community.common.security.dto.UserLoginDto;
import com.community.feign.contents.dto.UserDTO;
import com.community.feign.contents.user.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserLoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserFeign userFeign;


    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo){
        //非空校验
        if (StringUtils.isEmpty(loginVo.getMobile())){
            throw new CommunityException("手机号不能为空");
        }
        if (StringUtils.isEmpty(loginVo.getCode())){
            throw new CommunityException("验证码不能为空");
        }
        //判断验证码
        String key = String.format(RedisKey.LOGIN_SMS_KEY,loginVo.getMobile(),loginVo.getCode());
        Boolean delete = redisTemplate.delete(key);
        if (!delete){
            throw new CommunityException("验证码有误");
        }
        //判断是否为新用户
        UserDTO userDTO = userFeign.getUserByMobile(loginVo.getMobile());
        if (userDTO==null){
            //自动注册新用户
            userDTO= new UserDTO();
            userDTO.setMobile(loginVo.getMobile()); // 手机号必填的
            String mobileEnd = loginVo.getMobile().substring(loginVo.getMobile().length() - 4);
            userDTO.setUsername("comm-"+mobileEnd); // 自动生成的一个用户名
            userDTO = userFeign.save(userDTO); // 返回主键
        }
        userDTO.setOpenid(null);
        userDTO.setStatus(null);
        userDTO.setMobile(null);
        // 登录成功后需要生成Token对象
        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setUserId(userDTO.getId());
        userLoginDto.setCreateTime(new Date());
        //
        String token = JWTUtils.createToken("loginUser", userLoginDto);
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userInfo", JSON.toJSONString(userDTO));

        return new Result().ViewOk(data);

    }

}
